﻿using System;

namespace QQ2564874169.Core.Lock
{
    /// <summary>
    /// 异常锁。
    /// </summary>
    public sealed class ExceptionLockspace : ILockspace
    {
        private ILocker _locker;
        private string _key;

        public ExceptionLockspace(ILocker locker, string key, string ex = null)
        {
            if (locker == null)
                throw new ArgumentNullException(nameof(locker));
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException(nameof(key));

            _locker = locker;
            _key = key;
            ex = ex ?? key + " is locked";

            if (_locker.Lock(key) == false)
                throw new SpaceLockedException(ex);
        }

        public void Dispose()
        {
            _locker.UnLock(_key);
            _locker = null;
            _key = null;
        }
    }
}
